/*
 * @Author: xiaosihan
 * @Date: 2023-06-03 14:54:18
 * @Last Modified by: xiehangyunn
 * @Last Modified time: 2025-04-17 19:20:45
 */

//Group
import { BackSide, Group, MeshBasicMaterial, MeshStandardMaterial } from 'three';
import threeLoader from 'three-base/threeLoader';
import threeUtils from 'three-base/threeUtils';

import { BufferGeometry, Material, Mesh } from 'three';
// import editorStore from '../editorStore';
// import textureManager from '../textureManager';

export default class MockupMesh extends Group {
  constructor(url?: string) {
    super();
    url && this.loadModal(url);
  }

  // 加载完成状态
  _loaded = false;

  // 等待加载完成
  async awaitLoaded() {
    while (!this._loaded) {
      await new Promise((resolve) => setTimeout(resolve, 200));
    }
  }

  // 加载模型
  async loadModal(glb_url: string) {
    this._loaded = false;
    this.name = glb_url;

    const gltfobj = await threeLoader.loadModel(glb_url);

    gltfobj.traverse(async (obj: any) => {
      const mesh = obj as Mesh<BufferGeometry, Material>;
      if (mesh.isMesh) {
        ((mesh as Mesh).material as MeshBasicMaterial) = (
          (mesh as Mesh).material as MeshBasicMaterial
        ).clone();
        ((mesh as Mesh).material as MeshBasicMaterial).color.set('#ffffff');
      }
    });

    threeUtils.scaleTo(gltfobj, 10, ['x', 'y']);
    threeUtils.center(gltfobj);

    // 应用全部变换
    gltfobj.traverse((obj: any) => {
      const mesh = obj as Mesh;
      mesh.position.set(0, 0, 0);
      mesh.rotation.set(0, 0, 0);
      mesh.scale.set(1, 1, 1);
      if (mesh.isMesh) {
        mesh.geometry.applyMatrix4(mesh.matrixWorld);
        // (mesh.material as MeshStandardMaterial) = (mesh.material as MeshStandardMaterial).clone();
        // (mesh.material as MeshStandardMaterial).side = DoubleSide;
      }
    });

    this.clear();

    this.add(gltfobj);
    // 加载完成事件
    this.dispatchEvent<any>({ type: 'loaded' });

    this._loaded = true;
  }

  // 遍历模型
  traverseMesh(call: (mesh: Mesh<BufferGeometry, Material>) => void = () => { }) {
    this.traverse((obj) => {
      const mesh = obj as Mesh<BufferGeometry, Material>;
      if (mesh.isMesh) {
        call(mesh);
      }
    });
  }

  // updateMatrix(): void {
  //   const { goodsData } = editorStore;
  //   if (goodsData) {
  //     this.traverseMesh((mesh) => {
  //       const texture = textureManager.getTexture(mesh.name);
  //       const transparentTexture = textureManager.getTransparentTexture(mesh.name);
  //       if (texture) {
  //         if (mesh.material.side === BackSide) {
  //         } else {
  //           (mesh.material as MeshStandardMaterial).map =
  //             ([0].includes(goodsData.fillType) ? texture : transparentTexture) || null;
  //         }
  //       }
  //     });
  //   }
  //   super.updateMatrix();
  // }


}
